﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;

namespace ProgressBarTest.Controls
{
    /// <summary>
    /// 圆形进度条控件
    /// </summary>
    public class CycleProgressBar : Control
    {
        /// <summary>
        /// 进度条最小值
        /// </summary>
        private const int Minimum = 0;
        /// <summary>
        /// 进度条最大值
        /// </summary>
        private const int Maximum = 100;

        private Storyboard _storyboard;

        public CycleProgressBar()
        {
            DefaultStyleKey = typeof(CycleProgressBar);
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            _storyboard = GetTemplateChild("XArcStoryboard") as Storyboard;
            if (_storyboard != null)
            {
                _storyboard.Begin();
            }
        }

        public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
            "Text", typeof(string), typeof(CycleProgressBar), null);
        public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
            "Value", typeof(int), typeof(CycleProgressBar), null);
        public static readonly DependencyProperty AngleValueProperty = DependencyProperty.Register(
            "AngleValue", typeof(double), typeof(CycleProgressBar), null);

        /// <summary>
        /// 显示文字
        /// </summary>
        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        /// <summary>
        /// 进度值
        /// </summary>
        public int Value
        {
            get { return (int)GetValue(ValueProperty); }
            set
            {
                if (value < Minimum || value > Maximum)
                {
                    throw new ArgumentOutOfRangeException("value", "进度条值的范围是0-100");
                }
                AngleValue = 360.0 / Maximum * value;
                SetValue(ValueProperty, value);

                if (_storyboard != null)
                {
                    _storyboard.Begin();
                }
            }
        }

        /// <summary>
        /// 进度值转换为Arc角度
        /// </summary>
        public double AngleValue
        {
            get { return (double)GetValue(AngleValueProperty); }
            private set { SetValue(AngleValueProperty, value); }
        }
    }
}
